#include<stdio.h>
#include<stdlib.h>

#define eleType int


// 单向链表的结点定义
typedef struct ListNode
{
    /* data */
    eleType data;
    struct ListNode *next;

}ListNode;

//单向链表的定义
typedef struct linkedList
{
    /* data */
    struct ListNode *head;
    size_t size;
     
    
}linkedList;

//单向链表的创建
void LinkedListCreate(linkedList* list){
    list -> head = NULL;
    list -> size = 0;
} 
//创建


// 单项链表的销毁
void LinkedListDestroy(linkedList *list){
    while(list -> head){
        ListNode *temp = list->head;
        list-> head = list -> head  -> next;
        free(temp);
    }
    list -> size = 0;
}


//向链表list的第i个位置插入一个值为value的节点
void LinkedListInsert(linkedList* list,int i ,eleType value){
    if ( i<0 || i > list -> size){
        printf("Invalid index");
        return; 
    }

    ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
    newNode -> data = value;
    
    if(i == 0){
        newNode -> next = list -> head;
        list -> head = newNode;
    }else{
        ListNode* current = list -> head;
        for(int j=0;j<i-1;j++){
            current = current -> next;
        }
        newNode -> next = current -> next;
        current -> next = newNode;

    }
    list -> size++;


}

// 删除链表list的第i个位置的节点link
void LinkedListRemove(linkedList* list, int i){
    if(i < 0 || i >= list -> size){
        printf("Invalid index \n");
        return ;
    }
    if( i== 0){
        ListNode* next = list->head->next;
        free(list->head);
        list->head = next;
    }else {
        ListNode* current  = list -> head;
        for(int j=0;j< i-1 ;j++){
            current = current -> next;
        }
        ListNode* next = current -> next -> next;
        free(current -> next);
        current -> next = next;
    }
    list->size--;

}

//查找链表list中值为value的节点，并返回
ListNode* LinkedListFind(linkedList* list, eleType value){
    ListNode* current = list -> head;
    while(current){
        if(current -> data == value){
            return current;
        }
        current = current -> next;
    }
    return NULL;
}

//更新链表list中第i个节点的值为value

void LinkedListUpdate(linkedList* list,int i,eleType value){
     ListNode* node = LinkedListFind(list,i);
     if( node != NULL){
        node -> data = value;
     }else{
        printf("Invalid index \n");
     }
}

//打印链表
void LinkedListPrint(linkedList* list){
    ListNode* current = list->head;
    while (current)
    {
        printf("%d -> ",current ->data);
        current = current -> next;
    }
    printf("NULL\n");
}

int main(){


    linkedList* list = (linkedList*)malloc(sizeof(linkedList));
    LinkedListCreate(list);

    LinkedListInsert(list, 0, 1);
    LinkedListInsert(list, 1, 2);
    LinkedListInsert(list, 2, 3);
    LinkedListPrint(list);

    LinkedListUpdate(list, 1, 5);
    LinkedListPrint(list);

    LinkedListRemove(list, 0);
    LinkedListPrint(list);

    LinkedListDestroy(list);
    free(list);
    return 0;
}
